package common;

import center.ZkConfig;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2020-07-16
 * Time: 14:28
 *
 * @author zyh
 */
public class ZkUtil {

    private ZkConfig zkConfig;
    ZooKeeper zooKeeper;
    CountDownLatch countDownLatch;
    public  ZkUtil(ZkConfig zkConfig){
        if(zkConfig ==  null ){
            throw new IllegalArgumentException("参数错误");
        }
        this.zkConfig = zkConfig;
    }

    /**
     * 获取zookeeper
     * @return
     * @throws IOException
     */
    public ZooKeeper getZookeeper() throws IOException, InterruptedException {
        if(this.zooKeeper == null){
            countDownLatch = new CountDownLatch(1);
            zooKeeper = new ZooKeeper(zkConfig.getConnectString(),zkConfig.getSessionOutTime(),new ConnectWatch(countDownLatch));
            this.countDownLatch.await();
        }
        return zooKeeper;
    }

    /**
     * 关闭
     * @throws InterruptedException
     */
    public void close() throws InterruptedException {
        this.zooKeeper.close();
    }
}
